package com.z_talk.server.view;

import com.z_talk.core.enums.ResponseEnum;
import com.z_talk.core.message.ResponseMessage;
import com.z_talk.core.model.UserInfo;
import com.z_talk.core.model.UserModel;
import com.z_talk.core.vo.LoggerVO;
import com.z_talk.server.core.MessageHandler;
import com.z_talk.server.localization.LoggerLocalzation;
import com.z_talk.server.localization.NoticeLocalzation;
import com.z_talk.server.config.PropertiesUtil;
import com.z_talk.server.localization.UserLocalzation;
import com.z_talk.server.model.OnlineUserTableModel;
import com.z_talk.server.model.RegisterUserTableModel;


import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ServerView {
    private JPanel serverPanel;
    private JTabbedPane serverMenu;
    private JTextArea loggerMessage;
    private JTextArea messageConsole;
    private JButton send;
    private JLabel serverTitle;
    private JLabel serverMessage;
    private JTextArea message;
    private JPanel sendMessage;
    private JScrollPane onlineUserList;
    private JTable onlineUserTable;
    private JScrollPane registerUserList;
    private JTable registerUserTable;
    private JScrollPane loggerPanel;


    private List<UserInfo> registerUsers;
    private List<UserModel> onlineUsers;
    private String notice;
    private String IP;
    private int port;

    public ServerView() {
        loadData();
        init();
    }

    private void loadData() {
        registerUsers = UserLocalzation.loadUserList();
        onlineUsers = MessageHandler.copyOnWriteArrayList;
        notice = NoticeLocalzation.loadNotice();
        try {
            IP = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        port = Integer.parseInt(PropertiesUtil.configProp.getProperty("port"));
    }

    public void init(){
        JFrame jFrame = new JFrame("服务器");
        jFrame.setContentPane(this.serverPanel);
        jFrame.setVisible(true);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setSize(700,500);
        int x = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
        int y = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight();
        jFrame.setLocation((x - jFrame.getWidth()) / 2, (y-jFrame.getHeight())/ 2);
//        jFrame.setResizable(false);

        // 添加初始数据
        LoggerVO loggerVO = new LoggerVO("服务器启动");
        initLogger(loggerVO.getLogger());

        updateTitleMessage();

        OnlineUserTableModel onlineUserTableModel = new OnlineUserTableModel(onlineUsers);
        onlineUserTable.setModel(onlineUserTableModel);

        RegisterUserTableModel registerUserTableModel = new RegisterUserTableModel(registerUsers);
        registerUserTable.setModel(registerUserTableModel);

        updateMessage(notice);


        serverMenu.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                JTabbedPane jTabbedPane = (JTabbedPane)e.getSource();
                if (jTabbedPane.getSelectedIndex()==3){
                    message.requestFocus();
                }
            }
        });

        send.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String msg = message.getText();
                // 更新公告展示区域
                updateMessage(msg);
                LoggerVO loggerVO = new LoggerVO("管理员发送一条公告");
                updateLogger(loggerVO.getLogger());
                // 持久化公告
                NoticeLocalzation.saveNotice(msg);
                // 发送所有的在线用户
                ResponseMessage responseMessage = new ResponseMessage();
                responseMessage.setMessageType(ResponseEnum.NOTICE_RESPONSE);
                Map<String,Object> attr = new HashMap<>();
                attr.put(ResponseEnum.NOTICE_RESPONSE.getAttr(),msg);
                responseMessage.setAttribute(attr);
                try {
                    MessageHandler.sendMsg(responseMessage);
                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                }finally {
                    message.setText("");
                    message.requestFocus();
                }
            }
        });

    }

    public static void main(String[] args) {
        new ServerView();
    }

    public void initLogger(String msg){
        String logger = LoggerLocalzation.loadLogger();
        logger+="\n============↑↑↑历史记录↑↑↑=============";
        logger+="\n\n"+msg;
        loggerMessage.append(logger);
    }

    public void updateLogger(String msg){
        String logger = "\n"+msg;
        LoggerLocalzation.saveLogger(logger);
        loggerMessage.append("\n"+msg);
    }

    public void updateOnline(){
        List<UserModel> onlineUsers = MessageHandler.copyOnWriteArrayList;
        OnlineUserTableModel onlineUserTableModel = new OnlineUserTableModel(onlineUsers);
        onlineUserTable.setModel(onlineUserTableModel);
    }

    public void updateRegister(){
        List<UserInfo> registerUsers = UserLocalzation.loadUserList();
        RegisterUserTableModel registerUserTableModel = new RegisterUserTableModel(registerUsers);
        registerUserTable.setModel(registerUserTableModel);
    }

    public void updateMessage(String msg){
        messageConsole.setText(msg);
    }


    public void updateTitleMessage(){
        String titleMessage = "IP：{0}   port：{1}   在线人数：{2}";
        titleMessage = MessageFormat.format(titleMessage,IP,port,onlineUsers.size());
        serverMessage.setText(titleMessage);
    }
}
